#include "ring_queue.hpp"
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <unistd.h>
#include <string>

using namespace ns_ring_queue;
using namespace ns_task;

pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

void* product(void* args)
{
    RingQueue<Task>* rq = (RingQueue<Task>*)args;
    std::string s = "+-*/%";
    while(true)
    {
        //sleep(1);
        //int t = rand() % 100;
        int left = rand() % 30 + 1;
        int right = rand() % 10 + 1;
        char op = s[rand() % 5];
        Task t(left, right, op);
        rq->push(t);
        pthread_mutex_lock(&mtx);
        std::cout << "我是[" << pthread_self() << "], 发布的任务为 " << left << op << right << "=?" << std::endl;
        pthread_mutex_unlock(&mtx);
        //std::cout << "我是[" << pthread_self() << "], 生产者生产的数据是 " << t << std::endl;
    }
}

void* consume(void* args)
{
    RingQueue<Task>* rq = (RingQueue<Task>*)args;
    while(true)
    {
        sleep(1);
        //int data = 0;
        Task data;
        rq->pop(&data);
        pthread_mutex_lock(&mtx);
        std::cout << "我是[" << pthread_self() << "], 执行的任务为 " << data.d1 << data.op << data.d2 << "=" << data.run() << std::endl;
        pthread_mutex_unlock(&mtx);
        //std::cout << "我是[" << pthread_self() << "], 消费者消费的数据是 " << data << std::endl;
    }
}

int main()
{
    srand(time(nullptr));
    RingQueue<int>* rq = new RingQueue<int>();
    pthread_t c0, c1, c2, c3;
    pthread_t p0, p1, p2;
    pthread_create(&p0, nullptr, product, (void*)rq);
    pthread_create(&p1, nullptr, product, (void*)rq);
    pthread_create(&p2, nullptr, product, (void*)rq);

    pthread_create(&c0, nullptr, consume, (void*)rq);
    pthread_create(&c1, nullptr, consume, (void*)rq);
    pthread_create(&c2, nullptr, consume, (void*)rq);
    pthread_create(&c3, nullptr, consume, (void*)rq);

    pthread_join(p0, nullptr);
    pthread_join(p1, nullptr);
    pthread_join(p2, nullptr);

    pthread_join(c0, nullptr);
    pthread_join(c1, nullptr);
    pthread_join(c2, nullptr);
    pthread_join(c3, nullptr);
    delete rq;

    return 0;
}